<template>
  <div class="report-component">
    <!-- 左侧报告列表 -->
    <div class="report-sidebar">
      <div class="sidebar-header">
        <h2>报告列表</h2>
      </div>
      <div class="sidebar-content">
        <div class="new-report-menu-item" @click="createNewReport">
          <div class="menu-item-content">
            <div class="menu-item-left">
              <i data-v-cef5e0e4="" class="el-icon add-icon"
                ><svg data-v-cef5e0e4="" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
                  <path
                    fill="currentColor"
                    d="M480 480V128a32 32 0 0 1 64 0v352h352a32 32 0 1 1 0 64H544v352a32 32 0 1 1-64 0V544H128a32 32 0 0 1 0-64z"
                  ></path></svg
              ></i>
              <span>新增报告</span>
            </div>
          </div>
        </div>
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="reports.length > 0" class="report-list">
          <div
            v-for="report in reports"
            :key="report.id"
            class="report-item"
            :class="{ active: currentReport?.id === report.id }"
            @click="selectReport(report)"
          >
            <div class="report-info">
              <div class="report-title">{{ report.report_title }}</div>
              <div class="report-date">{{ formatDate(report.created_at) }}</div>
            </div>
            <div class="report-actions">
              <el-icon class="delete-icon" @click.stop="confirmDeleteReport(report)"
                ><Delete
              /></el-icon>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <div class="empty-icon">
            <el-icon><i-ep-files /></el-icon>
          </div>
          <div class="empty-text">暂无报告</div>
        </div>
      </div>
    </div>

    <!-- 右侧报告详情 -->
    <div class="report-detail">
      <ReportEditView
        v-if="currentReport && !isCreatingNewReport"
        :is-dark-mode="isDarkMode"
        :report-id="currentReport.id"
      />
      <AIReportGenerator
        v-else-if="isCreatingNewReport"
        :is-dark-mode="isDarkMode"
        :current-dataset="null"
        :dataset-fields="[]"
        @report-created="handleReportCreated"
      />
      <div v-else class="empty-detail">
        <el-empty description="请选择一个报告或新建报告" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import ReportEditView from '../../client/views/ReportEditView.vue'
import AIReportGenerator from '../../client/components/layout/AIReportGenerator.vue'
import { getMyReports, deleteReport } from '../../client/api/analysis'

defineProps({
  isDarkMode: {
    type: Boolean,
    default: false,
  },
})

// 报告列表
const reports = ref([])
const currentReport = ref(null)
const loading = ref(false)
const isCreatingNewReport = ref(false)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return (
    date.toLocaleDateString() +
    ' ' +
    date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  )
}

// 获取报告列表
const fetchReports = async () => {
  try {
    loading.value = true
    // 使用 /dk/sessions/get_my_reports 接口
    const response = await getMyReports()

    if (response.data && response.status === 'success') {
      reports.value = response.data || []
    } else {
      reports.value = []
    }
  } catch (error) {
    ElMessage.error('获取报告列表失败' + error)
  } finally {
    loading.value = false
  }
}

// 选择报告
const selectReport = (report) => {
  currentReport.value = report
  isCreatingNewReport.value = false
}

// 创建新报告
const createNewReport = () => {
  currentReport.value = null
  isCreatingNewReport.value = true
}

// 确认删除报告
const confirmDeleteReport = (report) => {
  ElMessageBox.confirm(`确定要删除报告"${report.report_title}"吗？删除后将无法恢复。`, '删除报告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleDeleteReport(report)
    })
    .catch(() => {
      // 用户取消删除操作
    })
}

// 处理删除报告
const handleDeleteReport = async (report) => {
  try {
    const response = await deleteReport(report.id)
    if (response.status === 'success') {
      ElMessage.success('报告删除成功')
      // 如果当前选中的报告被删除，重置当前报告
      if (currentReport.value?.id === report.id) {
        currentReport.value = null
        isCreatingNewReport.value = true
      }
      // 重新获取报告列表
      await fetchReports()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除报告失败:', error)
    ElMessage.error(`删除报告失败: ${error.message || '请重试'}`)
  }
}

// 处理新报告创建事件
const handleReportCreated = async (reportData) => {
  // 重新获取报告列表以确保新报告包含在内
  await fetchReports()

  // 查找刚创建的报告
  const newReport = reports.value.find((r) => r.id === reportData.id)

  if (newReport) {
    // 如果在列表中找到新创建的报告，则选择它
    currentReport.value = newReport
    isCreatingNewReport.value = false
  } else {
    // 如果未在列表中找到（可能是API响应延迟），手动创建一个临时对象
    currentReport.value = {
      id: reportData.id,
      report_title: reportData.title,
      description: reportData.requirements,
      created_at: new Date().toISOString(),
    }
    isCreatingNewReport.value = false
  }
}

// 组件挂载时获取报告列表
onMounted(() => {
  fetchReports()
  currentReport.value = null
  isCreatingNewReport.value = true
})
</script>

<style scoped>
.report-component {
  height: 100vh;
  width: 100%;
  display: flex;
  color: var(--el-text-color-primary);
  overflow: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 0px;
}

/* 左侧边栏样式 */
.report-sidebar {
  width: 240px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  box-shadow: var(--app-shadow-hover);
  height: 100%;
  overflow: visible;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  box-shadow: var(--app-shadow-hover);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--app-text-primary);
}

.sidebar-content {
  flex: 1;
  padding: 20px;
  overflow-y: visible;
}

/* 新增报告菜单项样式 */
.new-report-menu-item {
  border-radius: var(--app-radius-sm, 4px);
  margin-bottom: 12px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  border: 1px solid transparent;
  cursor: pointer;
  background-color: rgba(var(--el-color-primary-rgb), 0.1);
  border-color: rgba(var(--el-color-primary-rgb), 0.2);
}

.new-report-menu-item:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.15);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.new-report-menu-item .menu-item-content {
  padding: 10px 12px;
}

.new-report-menu-item .menu-item-left {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-color-primary);
  font-weight: 500;
}

.add-icon {
  font-size: 18px;
}

.menu-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.menu-item-left {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: calc(100% - 40px);
}

.report-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.report-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-radius: 6px;
  background-color: var(--el-fill-color-light);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid transparent;
}

.report-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-color: var(--el-border-color);
}

.report-item.active {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-5);
}

.report-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.report-title {
  font-weight: 500;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--el-text-color-primary);
}

.report-date {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 修改空状态下的按钮样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: var(--el-text-color-secondary);
  margin-bottom: 20px;
}

.new-report-btn {
  padding: 10px 20px;
  border-radius: var(--app-radius-sm, 4px);
  background-color: rgba(var(--el-color-primary-rgb), 0.1);
  border: 1px solid rgba(var(--el-color-primary-rgb), 0.2);
  color: var(--el-color-primary);
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  box-shadow: none;
}

.new-report-btn:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.15);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

/* 深色模式样式适配 */
.dark-mode .new-report-menu-item {
  background-color: rgba(var(--el-color-primary-rgb), 0.2);
  border-color: rgba(var(--el-color-primary-rgb), 0.3);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.dark-mode .new-report-menu-item:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.25);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.dark-mode .new-report-btn {
  background-color: rgba(var(--el-color-primary-rgb), 0.2);
  border-color: rgba(var(--el-color-primary-rgb), 0.3);
}

/* 加载状态 */
.loading-state {
  padding: 16px;
}

/* 右侧详情区域 */
.report-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.empty-detail {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dark-mode .report-item {
  background-color: #2a2a2a;
  border-color: transparent;
}

.dark-mode .report-item:hover {
  background-color: #333;
  border-color: #444;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.dark-mode .report-item.active {
  background-color: rgba(64, 158, 255, 0.2);
  border-color: rgba(64, 158, 255, 0.3);
}

/* 报告项操作按钮 */
.report-actions {
  display: flex;
  gap: 6px;
  opacity: 0;
  transition: var(--app-transition-normal, all 0.3s ease);
  align-items: center;
  margin-left: 8px;
}

.report-item:hover .report-actions {
  opacity: 1;
}

/* 删除图标样式 */
.delete-icon {
  cursor: pointer;
  color: var(--app-text-secondary, #909399);
  font-size: 16px;
  padding: 6px;
  border-radius: 50%;
  transition: all 0.3s ease;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon:hover {
  color: var(--el-color-danger);
  transform: scale(1.1);
  background-color: rgba(var(--el-color-danger-rgb), 0.1);
}

/* 深色模式适配 */
.dark-mode .delete-icon:hover {
  background-color: rgba(var(--el-color-danger-rgb), 0.2);
}
</style>
